package com.easthome.service.impl;

import com.easthome.entity.OrderGoods;
import com.easthome.entity.Orders;
import com.easthome.mapper.OrderGoodsMapper;
import com.easthome.mapper.OrdersMapper;
import com.easthome.pojo.form.OrdersAddForm;
import com.easthome.pojo.vo.CartItemVO;
import com.easthome.service.CartService;
import com.easthome.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

@Service
@Transactional
public class OrdersServiceImpl implements OrdersService
{

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private CartService cartService;

    @Autowired
    private OrderGoodsMapper orderGoodsMapper;

    @Override
    public String addOrder(OrdersAddForm form, Integer userId) {

        Orders orders=new Orders();
        orders.setStatus(1);
        orders.setAddressId(form.getAddressId());
        orders.setTotalPrice(form.getTotalPrice());
        orders.setBuyerId(userId);
        String uuid= UUID.randomUUID().toString().replace("-","").substring(0,8);
        orders.setOrderId(uuid);
        int r = ordersMapper.addOrder(orders);


        for(Integer goodsId:form.getGoodsIds()){
            OrderGoods ordersGoods = new OrderGoods();
            ordersGoods.setGoodsId(goodsId);
            ordersGoods.setOrderId(uuid);
            //找redis要数据

            CartItemVO cartItemVo= cartService.getCartItemVo(userId,goodsId);
            ordersGoods.setGoodsName(cartItemVo.getGoodsName());
            ordersGoods.setAmount(cartItemVo.getAmount());
            ordersGoods.setUnitPrice(cartItemVo.getUnitPrice());
            ordersGoods.setTotalPrice(cartItemVo.getTotalPrice());
            orderGoodsMapper.addOrderGoods(ordersGoods);
            cartService.removeCartItem(userId,goodsId);
        }

        return uuid;
    }

    @Override
    public int paySucess(String ordersId) {
        return ordersMapper.paySucess(ordersId);
    }
}
